package com.dingwen.treasure.jpa.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.dingwen.treasure.jpa.dao.QuartzInfoDao;
import com.dingwen.treasure.jpa.service.QuartzInfoService;
import com.dingwen.treasure.model.entity.jpa.QuartzInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * QuartzJobService 服务
 *
 * @author dingwen
 * @date 2022/03/13
 */
@Slf4j
@Service
public class QuartzInfoServiceImpl implements QuartzInfoService {

    /**
     * 定时任务信息 dao
     */
    @Resource
    private QuartzInfoDao quartzInfoDao;

    /**
     * 找到所有任务信息
     *
     * @return {@link List}<{@link QuartzInfo}>
     */
    @Override
    public List<QuartzInfo> findAll(Example<QuartzInfo> quartzInfoExample) {
        return quartzInfoDao.findAll(quartzInfoExample);
    }

    /**
     * 保存
     *
     * @param quartzInfo 定时任务信息
     */
    @Override
    public QuartzInfo save(QuartzInfo quartzInfo) {
        return quartzInfoDao.save(quartzInfo);
    }

    /**
     * 成功增量
     *
     * @param id 定时任务id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void incrementForSuccess(Long id) {
        quartzInfoDao.incrementForSuccess(id);
    }

    /**
     * 失败增量
     *
     * @param id 定时任务id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void incrementForFail(Long id) {
        quartzInfoDao.incrementForFail(id);
    }

    /**
     * 根据任务 id 查询该任务是否存在
     *
     * @param id
     * @return
     */
    @Override
    public Optional<QuartzInfo> findById(Long id) {
        return quartzInfoDao.findById(id);
    }

    /**
     * 按id删除
     *
     * @param id 定时任务主键
     */
    @Override
    public void deleteById(Long id) {
        quartzInfoDao.deleteById(id);
    }

    /**
     * 按id更新
     *
     * @param quartzInfo 定时任务信息
     */
    @Override
    public void updateById(QuartzInfo quartzInfo) {
        Assert.isTrue(ObjectUtil.isNotEmpty(quartzInfo.getId()), "定时任务更新是Id不能为空");
        quartzInfoDao.save(quartzInfo);
    }

}
